
import os
import time
import random

from matplotlib import pyplot
from dexen.user.libs import server_api, constants as dc

from libs import input_reading, constants
from libs.visualizer import RectangleVisualizer


""" GLOBALS """
script_api = api.GetTaskAPI()
boxes = input_reading.read_input()
cnt = 0


def draw_pareto(individuals = None):
    global cnt
    print "\nI am in draw pareto"
    if individuals == None:
        individuals = script_api.downloadLiveIndividuals(
            select = ("min_width", "min_height", 'orient', 'phenotype', 'area'),
            where = (
                ("area", dc.NOT_EQUAL, None)
            ),
            order_by = ("area", dc.ASC)
        ) 
        flag = True
    
    cnt += 1
    pyplot.figure(cnt)
    pyplot.scatter([individual['min_width'] for individual in individuals],
                   [individual['min_height'] for individual in individuals]
    )
    
    cur_time = time.time()
    pareto_fn = "pareto%s.png" %(cur_time)
    pyplot.savefig(os.path.join(constants.VISUALIZATION_DIR, pareto_fn))
    
    """
    output_fn = "output%s.txt" %(cur_time)
    f = open(os.path.join(constants.VISUALIZATION_DIR, output_fn), 'w')
    f.write("min_width, min_height, area\n")
    for ind in individuals:
        f.write("%s, %s, %s\n" %(ind['min_width'], ind['min_height'], int(ind['area'])))
    #draw_rectangles(individuals)
    f.close()
    """
    print "\nvisualization is done..."

def draw_rectangles(individuals):
    for id, individual in enumerate(individuals):
        rv = RectangleVisualizer(500, 500, boxes)
        rv.draw_individual(individual)
        rv.save_to_file(os.path.join(constants.VISUALIZATION_DIR, str(id) + ".png"))

